import time
import os
import re
import pandas
import openpyxl
from voice_handle import analyze_tone_and_speed2,analyze_tone_and_speed
from openpyxl.styles import Alignment
from collections import deque
from copy import deepcopy
import sys
from OllamaAPI import OllamaAPI
from prompt import Prompt
from constants import Constants


class Text2Excel:

    @classmethod
    def text2excel(cls,input_file,output_dir):
        """
        将txt文件转换为excel文件
        """
        xlsx_name = os.path.join(output_dir, os.path.basename(input_file).replace(".txt", ".xlsx")) # 初始化excel工作表
        wb = openpyxl.Workbook()  # 创建一个工作簿
        # 获取文件每一行
        with open(input_file, "r", encoding="utf-8") as f1:
            txt_line_list = list(f1.readlines())
        for index,line in enumerate(txt_line_list):  # 遍历每一行
            line = line.strip()
            if line == "":    # 跳过空行
                continue
            words_list = []      # 初始化一个列表，用于存储处理后的语句
            t_temp = re.split("(“.+?”)", line) 
            for t_temp_sub in t_temp:
                if t_temp_sub != "":
                    if len(t_temp_sub) > 100 and "”" not in t_temp_sub:
                        words_list.extend(t_temp_sub.split("。"))
                    else:
                        words_list.append(t_temp_sub)

            sheet_add_list = []
            for index,t in enumerate(words_list):    # 遍历处理后的语句
                if "“" not in t:
                    result = analyze_tone_and_speed(t)
                    seed = Constants.VOICE_BASE
                    sheet_add_list[index] = [seed,t,result["音调"],result["语速"]]
                else:
                    pass #todo
                    result = analyze_tone_and_speed2(t,f1.read())
                    sheet_add_list[index] = [result["角色"],t,result["音调"],result["语速"],result["情感"]]

            # 写入excel文件
            ws = wb.active
            for s in sheet_add_list:
                if isinstance(s,list):
                    ws.append(s)
                elif isinstance(s,dict):
                    ws.append(list(s.values()))
                else:
                    print("错误！！！",s)
        # 调整列宽
        cls.conf_exccel_column_width(ws,[10,50,10,10,10])

        wb.save(xlsx_name)
        wb.close()

    @classmethod
    def conf_exccel_column_width(cls,ws,column_width_list):
        """
        配置excel工作表的列宽
        """
        for index,width in enumerate(column_width_list):
            ws.column_dimensions[chr(65+index)].width = width

                

    